
// import productTopItemStyle from "@Styles/productTopItemStyle.scss?inline"
import {
    Button,
    message,
    Modal,
    Space,
    Spin,
    ImgDefault,
    Checkbox,
    Popover
} from "@bytedance/mona-ui"
import type {
    PlasmoCSConfig,
    PlasmoGetInlineAnchor,
    PlasmoGetStyle,
    PlasmoMountShadowHost
} from "plasmo"
import React, { useState } from "react"
import { Provider } from "react-redux"

import { PersistGate } from "@plasmohq/redux-persist/integration/react"

import { persistor, store, useAppDispatch, useAppSelector } from "~store"

import { upimageToAiImage, createAi, getResult, upImageTo1688, createWhiteAi } from '@Api/to1688Sys'
import { blobToBase64, calculateFileMD5, getObjectURL, dataURLtoBlob } from './tools'
import './index.scss'
// setactivityToolType

// export const getStyle: PlasmoGetStyle = () => {
//   const style = document.createElement("style")
//   style.textContent = productTopItemStyle
//   return style
// }

export const config: PlasmoCSConfig = {
    // matches: ["https://picman.1688.com/*"]
}

export const getInlineAnchor: PlasmoGetInlineAnchor = async () => {
    return document.querySelectorAll('dd')[1] as HTMLElement //document.querySelector('.module-cbu-picture').querySelector('[style="display: flex;"]') as HTMLElement
}


let clickYes = false
let clickTime = null

const Rex = new RegExp("https://picman.1688.com/*")
if (Rex.test(location.href)) {
    run()
}

function run() {
    if (clickYes) return
    setInterval(() => {
        const getOieyr = document.querySelector('.ui-dialog')
        if (getOieyr) {
            getOieyr.style.setProperty('height', "100%", 'important')
            getOieyr.style.setProperty('width', "100%", 'important')
        }
        const getIds = document.querySelector('#sys-ibank')
        if (getIds) {
            getIds.style.setProperty('height', "100%", 'important')
            getIds.style.setProperty('width', "100%", 'important')
        }
    }, 702)
    clickTime = setInterval(() => {
        const dockerIs = document.querySelector('.tab-upload')
        if (dockerIs) {
            dockerIs.click()
            clickYes = true
            clearTimeout(clickTime)
            clickTime = null
            // setTimeout(() => {
            //     // console.log('selectfilter', document.querySelector('#selectfilter'))
            //     document.querySelector('#selectfilter').click()
            // }, 1000)
        }
    }, 100)
}
// 店铺白名单
const shopWhiteList = ['龙港市逸闻电子商务商行']

const TaberTopBut = () => {
    // console.log('可以加载组建')
    const [loginImage, setLoginImage] = useState(false)
    const [upAiImageBox, setUpAiImageBox] = useState(false)
    const [upImgaes, setUpImgaes] = useState<any>([])
    function cheachByusn() {
        let isBuyShop = false
        shopWhiteList.forEach(item => {
            if (window.FEMetadata.loginId.includes(item)) {
                // setUpAiImageBox(true)
                isBuyShop = true
            }
        })
        if (!isBuyShop) {
            Modal.info({
                title: '提示',
                content: (<>
                    <Space direction="vertical" align="center" style={{
                        width: '93%'
                    }}>
                        <div>该功能未全量开放，请联系管理员</div>
                        <ImgDefault src="https://wtplug.oss-cn-hangzhou.aliyuncs.com/webimages/code/WechatIMG6.jpg?time=1730886377582" width={120} height={120}></ImgDefault>
                    </Space>
                </>),
                zIndex: 9999999,
                style: {
                    marginLeft: 0
                },
                bodyStyle: {
                    marginLeft: 0
                },
                okText: '知道了',
                onOk() {
                    // console.log('ok')
                }
            })

        }
        return isBuyShop
    }
    function getImageFile(e) {
        // 阻止冒泡
        e.stopPropagation()
        if (!cheachByusn()) return
        // return
        // var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
        // var viewportHeight = window.innerHeight || document.documentElement.clientHeight;

        // console.log('viewportWidth', viewportWidth)
        // console.log('viewportHeight', viewportHeight)
        // return
        // setUpAiImageBox(true)
        // const getSelectDom = document.querySelector('select')
        // console.log('getSelectDom', getSelectDom)

        // var selectedValue = getSelectDom.options[getSelectDom.selectedIndex].value;
        // console.log('selectedText', selectedValue)
        // console.log('wwwww', window)
        // return
        const input = document.createElement('input')
        input.type = 'file'
        input.multiple = true
        input.accept = 'image/*'
        input.click()
        input.onchange = () => {
            const files = input.files
            setUpAiImageBox(true)
            // setLoginImage(true)
            if (files) {
                const fileArray = Array.from(files)
                // fileArray.forEach()
                // 过滤大于5m到图片
                const filteredFiles = fileArray.filter(file => file.size <= 5 * 1024 * 1024 && file.type.startsWith('image/')).splice(0, 5)
                console.log('filteredFiles', filteredFiles)

                if (filteredFiles.length > 0) {
                    // const formData = new FormData()
                    // filteredFiles.forEach(file => {
                    //     formData.append('file', file)
                    // })
                    let getAlls = filteredFiles.map((file, index) => {
                        // setUpImgaes(prev => [...prev, { url: getObjectURL(file), status: 'loading' }])
                        const imageData = {
                            lodinStatus: true,
                            url: getObjectURL(file),
                            file: file,
                            id: index
                        }
                        setUpImgaes(prev => [...prev, imageData])
                        return new Promise((resolve, reject) => {
                            blobToBase64(file).then(async base64String => {

                                const md5 = await calculateFileMD5(file);
                                upimageToAiImage({
                                    md5,
                                    image: base64String,
                                    type: file.type,
                                    name: file.name,
                                    ailist: [],
                                    aistatus: false,
                                    statusAiContent: ''
                                }).then(res => {
                                    imageData.lodinStatus = false
                                    // imageData.url = res.url
                                    imageData.id = res._id
                                    console.log('imageData', imageData)
                                    setUpImgaes(prev => {
                                        const index = prev.findIndex(item => item.file === file)
                                        if (index !== -1) {
                                            prev[index] = imageData
                                        }
                                        return [...prev]
                                    })
                                    resolve(res.url)
                                    return res
                                })
                            })
                        })
                    })
                    Promise.all(getAlls).then(res => {
                        console.log('res', res)
                        // setLoginImage(false)
                    })


                    console.log('需要上传作图的图片')
                    // fetch('https://picman.1688.com/api/v1/picman/upload', {
                    //     method: 'POST',
                    // })
                }
            }
        }
    }
    function getaiconetng(item, func) {
        if (!cheachByusn()) return
        item.aistatus = true
        setUpImgaes(prev => [...prev])
        return new Promise((resolve, reject) => {
            func({ img: item.id }).then((res) => {

                let cinters = setInterval(() => {
                    getResult({ id: res }).then(res => {
                        if (res.status === 1) {
                            item.aistatus = false
                            item.statusAiContent = ''
                            console.log('成功')
                            if (res.data.target_list && res.data.target_list.length > 0) {
                                item.ailist = res.data.target_list.map(item => {
                                    return {
                                        url: item,
                                        checked: false
                                    }
                                })
                            } else {
                                item.ailist = [{
                                    url: res.data.target_url,
                                    checked: false
                                }]
                            }

                            resolve(true)
                            // console.log('item.ailist', item.ailist)
                            setUpImgaes(prev => [...prev])
                            clearInterval(cinters)
                            cinters = null
                        } else if (res.status === 2) {
                            item.aistatus = false
                            setUpImgaes(prev => [...prev])
                            // console.log('失败')
                            message.warn('创建失败请点击重试')
                            item.statusAiContent = '创建失败请点击重试'
                            clearInterval(cinters)
                            resolve(false)
                            cinters = null
                        }
                        // if (res && res.target_list && res.target_list.length) {
                        //     item.aistatus = false
                        //     console.log('成功')
                        //     item.ailist = res.target_list
                        //     setUpImgaes(prev => [...prev])
                        //     clearInterval(cinters)
                        //     cinters = null
                        // }
                    })
                }, 1000)
            })
        })

    }
    function createAiFunc(func) {
        const getAiIdContent = upImgaes.map(item => {
            return getaiconetng(item, func)

        })
    }
    const [upImageLodin, setUpImageLodin] = useState(false)
    function upImageFuncTo1688() {
        setUpImageLodin(true)

        upImgaes.map((item, index) => {
            if (!item.ailist || !item.ailist.length) {
                Modal.error({
                    title: '提示',
                    content: `请生成第${index + 1}张图片`,
                    zIndex: 9999999,
                })
                setUpImageLodin(false)
                throw new Error("请上传图片");
            }
            const someSelect = item.ailist.some(item => item.checked)
            console.log('someSelect', someSelect)
            if (!someSelect) {
                Modal.error({
                    title: '提示',
                    content: `请选择第${index + 1}张图片`,
                    zIndex: 9999999,
                })
                setUpImageLodin(false)
                throw new Error("请选择图片");
            }
        })
        const getAllPimg = upImgaes.map(item => {
            // 判断是有没有选择的图片

            // return someSelect ? item.ailist.filter(item => item.checked) : []
            return new Promise((resolve, reject) => {
                if (item.ailist && item.ailist.length) {
                    item.ailist.map(item => {
                        if (item.checked) {
                            // console.log('item.url', item.url)
                            const getImageblbo = new Image()
                            getImageblbo.src = item.url
                            // 图片跨域
                            getImageblbo.crossOrigin = 'anonymous'
                            getImageblbo.onload = async () => {
                                const canvas = document.createElement('canvas')
                                canvas.width = getImageblbo.width
                                canvas.height = getImageblbo.height
                                const ctx = canvas.getContext('2d')
                                ctx.drawImage(getImageblbo, 0, 0, getImageblbo.width, getImageblbo.height)
                                const dataURL = canvas.toDataURL('image/jpeg')
                                // console.log('dataURL', dataURL)
                                const blob = await dataURLtoBlob({
                                    dataURL, type: 'image/jpeg'
                                })
                                const md5name = calculateFileMD5(blob)
                                const file = new File([blob], `${md5name}.jpeg`, { type: 'image/jpeg' })
                                const forData = new FormData();
                                // console.log('file', file)
                                const getInputContent = document.querySelector('[name="_csrf_token"]')
                                const getSelectDom = document.querySelector('select')
                                // console.log('getSelectDom', getSelectDom)

                                var selectedValue = getSelectDom.options[getSelectDom.selectedIndex].value;
                                // console.log('getInputContent', getInputContent, getInputContent.value)
                                forData.append('isIframeMode', 'false')
                                forData.append('_csrf_token', getInputContent.value)
                                forData.append('source', 'offer_product')
                                forData.append('drawTxt', 'false')
                                forData.append('albumId', selectedValue)
                                forData.append('fname', `${md5name}.jpeg`)
                                forData.append('imgFile', file)
                                upImageTo1688(forData).then(res => {
                                    // console.log('res', res)
                                    resolve(res)
                                })
                            }

                            // fetch('https://picman.1688.com/api/v1/picman/upload', {
                            //     method: 'POST',
                            // })

                        }
                    })
                }
            })

        })
        Promise.all(getAllPimg).then(res => {
            console.log('res', res)
            setUpAiImageBox(false)

            // setUpAiImageBox(false)
            var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
            var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
            const innier = {
                width: viewportWidth,
                height: viewportHeight
            }
            const upsetTins = `${window.name}|layout|${JSON.stringify(innier)}`
            window.parent.postMessage(upsetTins, '*')
            window.postMessage(upsetTins, '*')
            setTimeout(() => {
                const upImageData = res.map(item => {
                    return {
                        id: item.dataList[0],
                        src: item.miniImgUrls[0],
                        bigSrc: item.imgUrls[0]
                    }
                })
                const putStr = `${window.name}|select|${JSON.stringify(upImageData)}`
                window.parent.postMessage(putStr, '*')
                window.postMessage(putStr, '*')
                setUpImageLodin(false)
            }, 500)


        })
    }
    function deleteselectImage(index) {
        upImgaes.splice(index, 1)
        setUpImgaes([...upImgaes])
        if (upImgaes.length == 0) {
            setUpAiImageBox(false)
        }
    }
    return (
        <>
            <Button id="selectfilter" style={{
                marginLeft: 10
            }} onClick={getImageFile}>批量上传并制作ai图片</Button>
            <Modal
                size="small"
                visible={upAiImageBox}
                title="批量AI图片"
                okText="上传并回传图片"
                cancelText=" 取消"
                onCancel={() => setUpAiImageBox(false)}
                zIndex={9999}
                width={1000}
                onOk={() => upImageFuncTo1688()}>
                <Spin spinning={upImageLodin}>
                    <Space>
                        <Space direction="vertical">
                            {upImgaes.map((item, index) => {
                                return <Space key={index}>
                                    <Spin spinning={!!(item.lodinStatus || item.aistatus)} >
                                        <Space direction="vertical">
                                            <span>原图</span>
                                            <Space direction="vertical" size={3} align="center">
                                                <ImgDefault imgSrc={item.url} width={60} height={60} alt="" />
                                                <Button size="mini" onClick={() => {
                                                    getaiconetng(item, createAi)
                                                }}>生成AI</Button>
                                                <Button size="mini" type="link" onClick={() => {
                                                    getaiconetng(item, createWhiteAi)
                                                }}>AI白底图</Button>
                                                <Button size="mini" type="link" style={{
                                                    color: "red"
                                                }} onClick={() => {
                                                    deleteselectImage(index)
                                                }}>删除</Button>
                                            </Space>
                                        </Space>
                                    </Spin>
                                    <Space direction="vertical">
                                        <span>AI图</span>
                                        <Space>
                                            <div className="hideScroll" style={{
                                                width: 867,
                                                height: 121,
                                                overflowX: "scroll",
                                                display: "flex",
                                                alignItems: "center",
                                                // 设置滚动条高度
                                            }}>
                                                {item.statusAiContent}
                                                {item.ailist && item.ailist.map((itemss, indesx) => {
                                                    console.log('aiUrl', item)
                                                    return <Popover content={<ImgDefault imgSrc={itemss.url} width={100} height={100} alt="" />} zIndex={99999999999999} key={indesx}><div className="selecAicont">
                                                        <ImgDefault onClick={() => {
                                                            item.ailist.map((itemwe) => {
                                                                itemwe.checked = false
                                                            })
                                                            itemss.checked = true
                                                            setUpImgaes(prev => [...prev])
                                                        }} imgSrc={itemss.url} width={60} height={60} alt="" style={{
                                                            marginRight: 10
                                                        }} />
                                                        <div className="sjer">
                                                            <Checkbox checked={itemss.checked} onChange={(e) => {
                                                                item.ailist.map((itemwe) => {
                                                                    itemwe.checked = false
                                                                })
                                                                itemss.checked = e.target.checked
                                                                setUpImgaes(prev => [...prev])
                                                            }}></Checkbox>
                                                        </div>
                                                    </div>
                                                    </Popover>
                                                })}
                                            </div>
                                        </Space>
                                    </Space>
                                </Space>
                            })}
                            <Space>
                                <Button onClick={() => createAiFunc(createAi)} size="mini">全部生成AI</Button>
                                <Button onClick={() => createAiFunc(createWhiteAi)} size="mini">全部白底图</Button>
                            </Space>

                        </Space>

                    </Space>
                </Spin>


            </Modal>
        </>

    )
}

const PlasmoInline = () => {
    return (
        <Provider store={store}>
            <PersistGate loading={null} persistor={persistor}>
                <TaberTopBut />
            </PersistGate>
        </Provider>
    )
}

export default PlasmoInline
